package com.danbay.framework.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author SJG
 *         2017/11/6.
 */
public class RedisClient {

    private final RedisTemplate redisTemplate;

    private final StringRedisTemplate stringRedisTemplate;

    public RedisClient(RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate) {
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 键是否存在
     *
     * @param key 键
     * @return boolean
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 保存字符串键值
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 保存字符串键值，并设置过期时间
     *
     * @param key     键
     * @param value   值
     * @param expires 过期时间(秒)
     */
    public void set(String key, String value, long expires) {
        stringRedisTemplate.opsForValue().set(key, value, expires, TimeUnit.SECONDS);
    }

    /**
     * 获取字符串值
     *
     * @param key 键
     * @return 字符串
     */
    public String get(String key) {
        Object value = stringRedisTemplate.opsForValue().get(key);
        return value == null ? null : value.toString();
    }

    /**
     * 查询键
     * @param pattern 正则
     * @return 键集合
     */
    public Set<String> keys(String pattern){
        return stringRedisTemplate.keys(pattern);
    }

    /**
     * 删除键
     *
     * @param key 键
     */
    public void del(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 保存hash的某个值
     *
     * @param key hash表的key
     * @param hk  值的key
     * @param hv  值
     */
    public void hset(String key, String hk, Object hv) {
        stringRedisTemplate.opsForHash().put(key, hk, hv == null ? "" : hv.toString());
    }

    /**
     * 获取hash表的某个值
     *
     * @param key hash表的key
     * @param hk  值的key
     * @return 值
     */
    public Object hget(String key, String hk) {
        return stringRedisTemplate.opsForHash().get(key, hk);
    }

    public <T> void setEntity(String key, T entity) {
        redisTemplate.opsForValue().set(key, entity);
    }

	public <T> void setEntity(String key, T entity, long expireSeconds) {
        this.redisTemplate.opsForValue().set(key, entity, expireSeconds);
    }

    public <T> T getEntity(String key) {
        return (T) redisTemplate.opsForValue().get(key);
    }
}
